package com.tf_cut.admin.agent.controller;

import com.alibaba.fastjson.JSON;
import com.tf_cut.admin.agent.vo.AgentAndAccountVo;
import com.tf_cut.admin.annotation.Decrypt;
import com.tf_cut.admin.annotation.Encrypt;
import com.tf_cut.admin.backend.api.BackEndApi;
import com.tf_cut.admin.common.pojo.PageInfo;
import com.tf_cut.admin.common.pojo.Result;
import com.tf_cut.admin.sys.sysauthority.service.SysAuthorityService;
import com.tf_cut.admin.sys.sysauthority.vo.SysAuthorityVo;
import com.tf_cut.admin.sys.syssetting.service.SysSettingService;
import com.tf_cut.admin.sys.sysuser.service.SysUserService;
import com.tf_cut.admin.sys.sysuser.vo.SysUserVo;
import com.tf_cut.admin.sys.sysuserauthority.service.SysUserAuthorityService;
import com.tf_cut.admin.sys.sysuserauthority.vo.SysUserAuthorityVo;
import com.tf_cut.admin.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/agent/")
@Slf4j
public class AgentController {
	@Autowired
	private BackEndApi agentApi;
	
    @Autowired
    private SysUserService sysUserService;
    
    @Autowired
    private SysSettingService sysSettingService;
	@Autowired
	private SysAuthorityService sysAuthorityService;

	@Autowired
	private SysUserAuthorityService sysUserAuthorityService;
	
	// 进入代理商清单页面
	@GetMapping("agentlist")
    public ModelAndView agentList() {
        return new ModelAndView("agent/agentlist", "agent", null);
    }
	
	// 进入新增代理商页面
	@GetMapping("agentinsert")
    public ModelAndView agentInsert() {
        return new ModelAndView("agent/agentinsert", "agent", null);
    }

    @GetMapping("agentbind")
	public ModelAndView agentbind(){
		return new ModelAndView("agent/agentBind", "agent", null);
	}
	
	// 进入修改代理商页面
	@GetMapping("agentinfo")
    public ModelAndView agentInfo(String agentId) {
		AgentAndAccountVo avo = null == agentId ? 
				new AgentAndAccountVo() : 
					JSON.parseObject(agentApi.getAgent(agentId),AgentAndAccountVo.class);
		avo.setInitPassword(sysSettingService.get("1").getData().getUserInitPassword());
        return new ModelAndView("agent/agentinfo", "agent", avo);
    }
	
	// 新增/修改代理商
	@SuppressWarnings("unchecked")
	@PostMapping("saveAgent")
	@Decrypt
    @Encrypt
    public Result<AgentAndAccountVo> saveAgent(AgentAndAccountVo avo) {
		String rtnJson = null;
		Result<AgentAndAccountVo> result = Result.of(avo,true);
		AgentAndAccountVo nameV = new AgentAndAccountVo();
		nameV.setAgentName(avo.getAgentName());
		String nameRes = agentApi.findListAgentNoPage(JSON.toJSONString(nameV));
		List<AgentAndAccountVo> nameList = JSON.parseArray(nameRes,AgentAndAccountVo.class);

		if(StringUtils.isEmpty(avo.getAgentId())) {

			if(!nameList.isEmpty()){
				result = Result.of(avo,false,"代理商名称重复");
			}

			if(!result.isFlag()){
				return result;
			}

			try {
				SysUserVo retSysUserVo = sysUserService.initUser(avo.getAgentName(),StringUtils.isEmpty(avo.getLoginName()) ?
						avo.getAgentPhone() : avo.getLoginName(),"AGENT_USER").getData();	// 先注册系统用户

				avo.setLoginId(retSysUserVo.getUserId());
				avo.setAgentState("Y"); // 默认不冻结
				avo.setParentAgentId("0");
				rtnJson = agentApi.insertAgentAndAccount(JSON.toJSONString(avo));	// 再注册代理商用户
				result = JSON.parseObject(rtnJson, Result.class);

			} catch (Exception e) {
				log.error(e.getMessage(),e);
				// 异常处理
				avo.setLoginId(null);
				avo.setLoginName(null);
				avo.setAgentId(null);
				result = Result.of(avo);
				result.setFlag(false);
			}
				
		} else {
			Result<AgentAndAccountVo> result1 = Result.of(avo);
			nameList.forEach(vo -> {
				if(!vo.getAgentId().equalsIgnoreCase(avo.getAgentId())){
					result1.setFlag(false);
					result1.setMsg("代理商名称重复");
				}
			});

			if(!result1.isFlag()){
				return result1;
			}

			rtnJson = agentApi.updateAgentInfo(JSON.toJSONString(avo));
			result = JSON.parseObject(rtnJson, Result.class);
		}
		
		return result;
		
    }

	private boolean saveAgentAuthority(AgentAndAccountVo avo, SysUserVo save) {
		List<SysAuthorityVo> seller_user = this.sysAuthorityService.list(SysAuthorityVo.builder().authorityName("AGENT_USER").build()).getData();
		if(seller_user==null||seller_user.isEmpty()){
			return true;
		}
		SysUserAuthorityVo build = SysUserAuthorityVo.builder().userId(save.getUserId())
				.authorityId(seller_user.get(0).getAuthorityId()).createTime(new Date()).build();
		sysUserAuthorityService.save(build);
		return false;
	}

	// 代理商清单页面翻页
	@SuppressWarnings("unchecked")
	@PostMapping("agentlist/page")
	@Decrypt
    @Encrypt
    public Result<PageInfo<AgentAndAccountVo>> page(AgentAndAccountVo avo) {
	
        String json = JSON.toJSONString(avo);
        json = agentApi.findListAgent(json);
        return Result.of(JSON.parseObject(json, PageInfo.class));
    }
	
	// 代理商清单页面翻页
	@PostMapping("agentlist/list")
	@Decrypt
    @Encrypt
    public Result<List<AgentAndAccountVo>> list(AgentAndAccountVo avo) {
	
        String json = JSON.toJSONString(avo);
        json = agentApi.findListAgentNoPage(json);
        return Result.of(JSON.parseArray(json, AgentAndAccountVo.class));
    }
	
	// 冻结（Y）/删除（D）/解冻（N） 代理商
	@SuppressWarnings("unchecked")
	@RequestMapping("operation")
	public Result<Boolean> operation(AgentAndAccountVo avo) {
		Result<Boolean> result = JSON.parseObject(agentApi.operationAgent(avo.getAgentId(),avo.getAgentState()),Result.class);
		SysUserVo suv = sysUserService.get(avo.getLoginId()).getData();
		if(result.isFlag() && "N".equals(avo.getAgentState())) {
			suv.setValid("Y");
		} else
			suv.setValid("N");
		sysUserService.save(suv);
		
		return result;
	}
	
	@PostMapping("resetpass")
	@Decrypt
    @Encrypt
	public Result<Boolean> resetpass( AgentAndAccountVo avo) {
		sysUserService.resetPassword(avo.getLoginId());
		return Result.of(true);
	}

	@PostMapping("qryUnBindAgent")
	public Result<List<AgentAndAccountVo>> qryUnBindAgent(AgentAndAccountVo avo){
		String agentId = avo.getAgentId();
		String jsonData = agentApi.qryUnBindAgent(agentId);
		List<AgentAndAccountVo> data = JSON.parseArray(jsonData,AgentAndAccountVo.class);
		return Result.of(data);
	}

	@PostMapping("bindAgent")
	public Result<String> bindAgent(String agentId,String agentIds){
		List<String> list = new ArrayList<>();
		list.add(agentIds);
		return Result.of(agentApi.bindAgent(agentId,JSON.toJSONString(list)));
	}

	@PostMapping("unbindAgent")
	public Result<String> unbindAgent(String agentId){
		return Result.of(agentApi.unbindAgent(agentId));
	}
}
